package org.shan.lis.net;

import org.shan.lis.common.serial.IReciver;
import org.shan.lis.common.serial.Serial;
import org.shan.lis.utils.LogUtils;
import org.shan.mq.common.MqttMessageFactory;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import gnu.io.SerialPort;
import io.netty.buffer.ByteBufUtil;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.handler.codec.mqtt.MqttUtils;

/**
 * Created by amanda.shan on 2019/8/29.
 */
public class SerialMqClient extends Serial{

    private static AtomicInteger requestId = new AtomicInteger(0);

    public SerialMqClient(String portName) {

        super(portName, 115200, SerialPort.PARITY_NONE);
        setReciver(new IReciver() {
            @Override
            public void recive(byte[] bs, int len) {

                LogUtils.d("reacive:"+ByteBufUtil.hexDump(bs, 0, len));
            }
        });
    }


    public void register() throws IOException {
        MqttMessage message = MqttMessageFactory
                .createConnectMessage("shan", "123456", 100000000);
        byte[] bytes = MqttUtils.encode(message);

        send(bytes);

    }

    public void ping() throws IOException {

        MqttMessage message = MqttMessageFactory.createPingReqMessage();
        byte[] bytes = MqttUtils.encode(message);

        send(bytes);
    }

    public void push(String s) throws IOException {

        short id = (short) requestId.getAndIncrement();
        MqttMessage message = MqttMessageFactory
                .createPublishMessage(MqttQoS.AT_MOST_ONCE, "shydata", id, s);

        byte[] bytes = MqttUtils.encode(message);

        System.out.println("開始發送");
        send(bytes);

        System.out.println(ByteBufUtil.hexDump(bytes));

        System.out.println("發送成功");
    }



    public static void main(String[] args) throws Exception {

        MqttMessage message = MqttMessageFactory.createPingReqMessage();
//        byte[] bytes = MqttUtils.encode(message);

        message = MqttMessageFactory
                .createConnectMessage("shan", "123456", 20000);
        byte[] bytes = MqttUtils.encode(message);

        System.out.println(ByteBufUtil.hexDump(bytes));
    }

}
